<!-- @format -->

<script setup>
	import { ref } from 'vue'

	const model = defineModel()

	// 是否处于编辑状态
	const isEdit = ref(false)

	// 双击
	const onDblClick = () => {
		isEdit.value = true
	}

	// 在输入框上敲击了回车
	const onEnter = (e) => {
		// 获取输入框的值，并去除首尾空格
		const tagName = e.target.value.trim()
		if (tagName) {
			// 如果有值，需要把这个同步到父组件中（直接修改 model ）
			model.value = tagName
		}
		// 敲完回车，不管输入框有没有值，都要让输入框消失
		isEdit.value = false
	}
</script>

<template>
	<div class="my-tag">
		<input
			v-focus
			v-if="isEdit"
			class="input"
			type="text"
			:value="model"
			@blur="isEdit = false"
			placeholder="输入标签"
			@keydown.enter="onEnter" />
		<div
			class="text"
			v-else
			@dblclick="onDblClick">
			{{ model }}
		</div>
	</div>
</template>

<style lang="scss" scoped>
	.my-tag {
		cursor: pointer;
		.input {
			appearance: none;
			outline: none;
			border: 1px solid #ccc;
			width: 100px;
			height: 40px;
			box-sizing: border-box;
			padding: 10px;
			color: #666;
			&::placeholder {
				color: #666;
			}
		}
	}
</style>
